#!/usr/bin/env python3

import re
import sys

# go-swagger wants "response" structs to live inside a field named "Body".
# Rather than change the actual response structs to use this field, this script
# iterates over the responses in responses.go and generates a wrapper for
# go-swagger to use while it generates swagger.json. These wrappers aren't used
# by any of algorand's code -- they're just hints for go-swagger.

if __name__ == "__main__":
	friendly_name_regex = re.compile("//.*friendly:(.*)")
	type_regex = re.compile("type (.*Response) struct")
	response_types = []

	if len(sys.argv) != 2:
		print("output file is required")
		exit(-1)

	n = 0
	with open("responses.go", "r") as fin:
		line = fin.readline()
		while line:
			# Parse friendly name
			match = friendly_name_regex.match(line)
			if match:
				friendly_name = match.group(1)
				# Parse type name
				line = fin.readline()
				if not line:
					break
				match = type_regex.match(line)
				if match:
					n += 1
					type_name = match.group(1)
					response_types.append((friendly_name, type_name))
			line = fin.readline()

	with open(sys.argv[1], "w") as fout:
		fout.write("package kmdapi\n")
		for friendly_name, type_name in response_types:
			fout.write("\n// Swagger{} is an autogenerated wrapper from genSwaggerWrappers.py\n".format(friendly_name))
			fout.write("// swagger:response {}\n".format(friendly_name))
			fout.write("type Swagger{} struct {{\n".format(friendly_name))
			fout.write("\t// in:body\n")
			fout.write("\tBody {}\n".format(type_name))
			fout.write("}\n")
	print("generated {} wrappers".format(n))
